<template>
  <div id="app">
    <div class="box">
      <div v-if="showName">{{name}}</div>
      <input type="text" v-model="text">
      <hr>
      <button @click="addGood">添加</button>
      <ul>
        <li v-for="(good,index) in goods" :key="index">
          {{good.text}}
          <br>
          ￥:{{good.price}}
          <button @click="addCart(index)">添加购物车</button>
        </li>
      </ul>
      <hr>
      <Cart :name="name"></Cart>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import Cart from "./components/Cart";
export default {
  name: "app",
  data() {
    return {
      name: "zixuan",
      showName: true,
      text: "",
      goods: []
    };
  },
  provide:{
    //等于全局变量，向下传递
  },
  components: {
    Cart
  }, 
  async created() {
    try {
      const res = await axios.get("/api/goods");
      this.goods = res.data.list;
    } catch (error) {
      console.log(error);
    };

    setTimeout(() => {
      this.showName = false;
    }, 2000);
  },
   methods: {
    addGood() {
      if (this.text) {
        this.goods.push({ text: this.text });
        this.text = "";
      }
    },
    addCart(i) {
      const good = this.goods[i];
      this.$bus.$emit("addCart", good);
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  color: #2c3e50;
  line-height: 24px;
  font-size: 13px;
}
.box {
  padding: 10px;
  margin: 0 auto;
  width: 500px;
}
</style>